//
//  ReplyVC.swift
//  Employee
//
//  Created by swordjoy on 2017/3/29.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import UIKit
import Photos

class ReplyVC: BaseVC {

  var orderId: String!
  var didSuccess: VoidClosure?
  
  fileprivate var contentV: UIView!
  fileprivate var textV: UITextView!
  fileprivate var selectImageV: ImageSelectV!
  fileprivate var tipLabel: UILabel!
  
  fileprivate var okButton: UIButton!
  fileprivate var selectImagePopV: SelectImagePopV!
    
    fileprivate var assets: [PHAsset] = []
    fileprivate var assetIdentifier = ""
    
  fileprivate var replyProgress = Progress(totalUnitCount: 1)
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = GlobalConfig.BGWhiteColor
    title = "回复"
    
    create()
    closure()
    
    textV.becomeFirstResponder()
    
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
   
    GlobalConfig.baiduStatisticsPageViewStart("工单回复")
  }
  
  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    
    GlobalConfig.baiduStatisticsPageViewEnd("工单回复")
  }
  
  deinit {
    SJApp.log("ReplyVC deinit")
  }

}

// MARK: - action

extension ReplyVC {
  
  fileprivate func takePhoto() {
    
    if self.assets.count >= 4 {
      SJHint.show("你已经选择了四张啦")
      return
    }
    
    if GlobalConfig.isAuthorizationVideo() {
      let imagePicker = UIImagePickerController()
      imagePicker.delegate = self
      imagePicker.sourceType = .camera
      self.present(imagePicker, animated: true, completion: nil)
    }
    
  }
  
  @objc fileprivate func reply() {
    SJApp.endEdit()
    
    // 没有图片
    if assets.isEmpty {
      
      SJApp.showHUD(in: navigationController!.view)
      let _ = WorkorderRequest.shared.handleOrder(type: "REPLY", workOrderId: orderId, staffId: "", replyContent: textV.text, images: "", success: {
        
        SJApp.hideHUD(in: self.navigationController!.view)
        SJHint.show("回复成功!")
        self.navigationController?.popViewController(animated: true)
        
        if let temp = self.didSuccess { temp() }
        
      }, failure: { 
        SJApp.hideHUD(in: self.navigationController!.view)
      })
      
      return
      
    }
    
    // 获取图片

    SJApp.showHUD(in: navigationController!.view)
    
    var tempImageData: [Data] = []
    let tempImages = PhotoHelper.fetchOriginalPhotos(with: assets)
    for item in tempImages {
        tempImageData.append(item.uploadData)
    }
    
    let _ = FileRequest.shared.uploadImages(datas: tempImageData, progressClosure: { (progress) in
      
    }) { (ids) in
      
      let tempIds = ids.map({
        return $0.fileId
      })
      
      let imageIdsString = tempIds.joined(separator: ",")
      
      let _ = WorkorderRequest.shared.handleOrder(type: "REPLY", workOrderId: self.orderId, staffId: "", replyContent: self.textV.text, images: imageIdsString, success: {
        
        SJApp.hideHUD(in: self.navigationController!.view)
        
        SJHint.show("回复成功!")
        
        self.navigationController?.popViewController(animated: true)
        
        if let temp = self.didSuccess { temp() }
        
      }, failure: {
        SJApp.hideHUD(in: self.navigationController!.view)
      })
      
    }
    
  }
  
  @objc fileprivate func back() {
    
    navigationController?.popViewController(animated: true)
    
  }

}

// MARK: - PhotoPickerDelegate
extension ReplyVC: PhotoPickerDelegate {
    
    func photoPickerDidFinishSelected(_ assets: [PHAsset]) {
        self.assets = assets
        self.selectImageV.assets = self.assets
    }
    
}

// MARK: - UIImagePickerControllerDelegate,UINavigationControllerDelegate
extension ReplyVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
  
  func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else {
            return
        }
    
    UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(image:didFinishSavingWithError:contextInfo:)) , nil)
    
        runOnMainThread({
            picker.dismiss(animated: true) {
                
            }
        })
    
//        PHPhotoLibrary.shared().performChanges({
//            let request = PHAssetChangeRequest.creationRequestForAsset(from: image)
//            self.assetIdentifier = request.placeholderForCreatedAsset?.localIdentifier ?? ""
//        }) { (finish, error) in
//            if nil != error {
//                SJHint.show("获取照片失败, 请重新拍摄")
//                return
//            }
//            else {
//                let tempAssets = PHAsset.fetchAssets(withLocalIdentifiers: [self.assetIdentifier], options: nil)
//                guard let asset = tempAssets.firstObject else {
//                    SJHint.show("获取照片失败, 请重新拍摄")
//                    return
//                }
//                self.assets.append(asset)
//                self.selectImageV.assets = self.assets
//                runOnMainThread({
//                    picker.dismiss(animated: true) {
//                        
//                    }
//                })
//            }
//
//        }
    }
    func image(image: UIImage, didFinishSavingWithError: NSError?, contextInfo: AnyObject) {
        
        if didFinishSavingWithError != nil {
            return
        }
        let options = PHFetchOptions()
        options.sortDescriptors = [NSSortDescriptor.init(key: "creationDate", ascending: false)]
        let assetsFetchResults = PHAsset.fetchAssets(with: options)
        
        guard let asset = assetsFetchResults.firstObject else {
            SJHint.show("获取照片失败, 请重新拍摄")
            return
        }
        self.assets.append(asset)
        self.selectImageV.assets = self.assets
    }
  func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    runOnMainThread({
        picker.dismiss(animated: true) {
            
        }
    })
  }
  
}


// MARK: - fileprivate

extension ReplyVC {
  
  
  fileprivate func closure() {
    
    selectImagePopV.takePhotoClosure = { [unowned self] in self.takePhoto() }
    
    selectImagePopV.selectClosure = { [weak self] in
        guard let strongSelf = self else {
            return
        }
        
        let photoPicker = PhotoPicker(selectedCount: 0, maxCount: 4, delegate: strongSelf)
        if  let asses = self?.assets {
            photoPicker.selectedAsset = asses
        }
        strongSelf.navigationController?.pushViewController(photoPicker, animated: true)
    }
    
    selectImageV.addPhotoClosure = { [unowned self] in
      SJApp.endEdit()
      self.selectImagePopV.show(in: self.navigationController!.view!)
    }
    
    selectImageV.deleteClosure = { [unowned self] index in
        if (index + 1) <= self.assets.count {
            self.assets.remove(at: index)
        }
    }
    
  }
  
  fileprivate func create() {
    
    okButton = ObserveButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
    okButton.setTitle("确定", for: .normal)
    okButton.setTitleColor(GlobalConfig.TextLightColor, for: .normal)
    okButton.addTarget(self, action: #selector(reply), for: .touchUpInside)
    okButton.titleLabel?.font = GlobalConfig.system16Font
    okButton.isSelected = false
    okButton.contentHorizontalAlignment = .right
    let rightItem = UIBarButtonItem(customView: okButton)
    navigationItem.rightBarButtonItem = rightItem
    
    self.addBackTitleItem(title: "取消")
    
    
    contentV = UIView()
    view.addSubview(contentV)
    contentV.backgroundColor = UIColor.white
    contentV.snp.makeConstraints { (make) in
      make.left.equalTo(10)
      make.top.equalTo(10)
      make.right.equalTo(-10)
      make.height.equalTo(340)
    }
    contentV.layer.cornerRadius = 4
    contentV.clipsToBounds = true
    
    textV = UITextView()
    contentV.addSubview(textV)
    textV.font = GlobalConfig.system16Font
    textV.textColor = GlobalConfig.TextDeepColor
    textV.delegate = self
    textV.snp.makeConstraints { (make) in
      make.left.top.equalTo(15)
      make.right.equalTo(-15)
      make.height.equalTo(185)
    }
    
    selectImageV = ImageSelectV(frame: CGRect(x: 0, y: 200, width: UIScreen.width - 20, height: 100))
    contentV.addSubview(selectImageV)
    
    tipLabel = UILabel()
    contentV.addSubview(tipLabel)
    tipLabel.text = "最多可以添加4个附件"
    tipLabel.font = GlobalConfig.system12Font
    tipLabel.textColor = GlobalConfig.TextLightColor
    tipLabel.snp.makeConstraints { (make) in
      make.top.equalTo(selectImageV.snp.bottom).offset(15)
      make.left.equalTo(15)
    }
    
    selectImagePopV = SelectImagePopV(frame: UIScreen.main.bounds)
  }
}

// MARK: - UITextViewDelegate
extension ReplyVC: UITextViewDelegate {
  
    func textViewDidChange(_ textView: UITextView) {
        okButton.isSelected = !textView.text.isEmpty

    }
  
}
